package com.ruoyi.books.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.books.service.IColumnService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ColumnServiceImpl implements IColumnService {
    private static final String KEY = "column:";

    @Resource
    private RedisTemplate stringRedisTemplate;

    @Override
    public List<Map> getColumn(String pageName, Long tenant) {
        List<Map> maps = new ArrayList<>();
        String json = (String) stringRedisTemplate.opsForValue().get(KEY + pageName + ":" + tenant);
        JSONArray jsonArray = JSONObject.parseArray(json);
        if (CollectionUtil.isNotEmpty(jsonArray)) {
            for (Object object : jsonArray) {
                Map map = (Map) object;
                maps.add(map);
            }
        }
        return maps;
    }

    @Override
    public Boolean uploadColumn(String pageName, Long userId, List<Map> list) {
        boolean result = false;
        try {
            String maps = JSONObject.toJSONString(list);
            stringRedisTemplate.opsForValue().set(KEY + pageName + ":" + userId, maps);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

